package me.jiatao.redpacket.service;

import android.app.Notification;
import android.app.PendingIntent;
import android.graphics.Rect;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import me.jiatao.redpacket.util.SPDataUtils;
import me.jiatao.redpacket.util.ScreenUtil;

/**
 * 抢红包辅助
 *
 * @author Tyhj
 * @date 2019/6/30
 */

public class RedpacketService extends BaseAccessbilityService {

    public static boolean isCloseFail = true;
    /**
     * 单独抢一个群
     */
    public static boolean isSingle = true;

    /**
     * 抢自己发出的红包
     */
    //public static boolean isSelf = true;
    /**
     * 暂停抢红包
     */
    public static boolean isPause = false;

    /**
     * 微信包名 1
     */
    private static final String WX_PACKAGE_NAME = "com.tencent.mm";

    /**
     * 红包标识字段 1
     */
    public static final String HONG_BAO_TXT = "[微信红包]";
    /**
     * 详情界面的聊天List 的ID 1
     */
    public static final String DETAIL_CHAT_LIST_ID = "com.tencent.mm:id/an3";
    /**
     * 红包消息ID 1
     */
    private static final String AUM_ID = "com.tencent.mm:id/aag";
    /**
     * 已领取文本ID 1
     */
    private static final String AUL_ID = "com.tencent.mm:id/r0";
    /**
     * 红包打开界面元素ID 1
     */
    private static final String RED_PACKET_DIALOG_ID = "com.tencent.mm:id/deb";
    /**
     * 打开红包按钮 1
     */
    private static final String RED_PACKET_OPEN = "com.tencent.mm:id/dan";
    /**
     * 红包领取详情页ID 1
     */
    private static final String RED_PACKET_HISTORY = "com.tencent.mm:id/d_i";
    /**
     * 红包失败界面,关闭按钮ID 1
     */
    private static final String FAIL_CLOSE_ID = "com.tencent.mm:id/dej";
    /**
     * 联系人列表选项的[微信红包]的ID 1
     */
    private static final String HUMAN_LIST_TXT_ID = "com.tencent.mm:id/cyv";

    /**
     * 头像ID  com.tencent.mm:id/are 1
     */
    private static final String AVATAR_ID = "com.tencent.mm:id/tm";

    /**
     * 联系人列表 1
     */
    private static final String HUMAN_LIST = "com.tencent.mm:id/dg2";

    /**
     * 红包的开字在屏幕中的比例
     */
    private static final float POINT_Y_SCAL = 0.641F;

    /**
     * 获取屏幕宽高
     */
    int screenWidth = ScreenUtil.SCREEN_WIDTH;
    int screenHeight = ScreenUtil.SCREEN_HEIGHT;


    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        //暂停
        if (isPause) {
            return;
        }

        String packageName = event.getPackageName().toString();
        if (!packageName.contains(WX_PACKAGE_NAME)) {
            //不是微信就退出
            return;
        }

        //通知栏消息，判断是不是红包消息
//        if (event.getParcelableData() != null && event.getParcelableData() instanceof Notification) {
//            Notification notification = (Notification) event.getParcelableData();
//            //获取通知消息详情
//            String content = notification.tickerText.toString();
//            //解析消息
//            String[] msg = content.split(":");
//            String text = msg[1].trim();
//            if (text.contains(HONG_BAO_TXT)) {
//                PendingIntent pendingIntent = notification.contentIntent;
//                try {
//                    //点击消息，进入聊天界面
//                    pendingIntent.send();
//                } catch (PendingIntent.CanceledException e) {
//                    e.printStackTrace();
//                }
//            }
//        }

        /**
         * 获取聊天消息列表List控件
         */
        AccessibilityNodeInfo nodeInfo = findViewByID(DETAIL_CHAT_LIST_ID);
        //这个消息列表不为空，那么肯定在聊天详情页
        if (nodeInfo != null) {
            //判断有没有未领取红包并进行点击
            clickItem(nodeInfo);
            return;
        }

        /**
         * 当前为红包弹出窗（那个开的那个弹窗）
         */
        if (findViewByID(RED_PACKET_DIALOG_ID) != null) {
            //进行红包开点击
            clickOpen();
            return;
        }

        /**
         * 红包领取后的详情页面，自动返回
         */
        if (findViewByID(RED_PACKET_HISTORY) != null) {

            int closeTime = SPDataUtils.getInstance().getInt(SPDataUtils.CLOSE_PACKET_VIEW_TIME_KEY);
            if (closeTime != 0) {
                SystemClock.sleep(1000 * closeTime);
            }
            //返回聊天界面
            performGlobalAction(GLOBAL_ACTION_BACK);
            //如果不是专抢一个群
            if (!isSingle) {
                SystemClock.sleep(50);
                performGlobalAction(GLOBAL_ACTION_BACK);
            }
            return;
        }

        /**
         * 在最近聊天列表，检测有没有红包消息出现
         */
        nodeInfo = findViewByID(HUMAN_LIST);
        //联系人列表
        if (nodeInfo != null) {
            //判断最近聊天列表有没有未领取红包
            clickHumanItem(nodeInfo);
            return;
        }


        /**
         * 关闭领取失败界面
         */
//        if (isCloseFail) {
//            SystemClock.sleep(200);
//            if (findViewByID(FAIL_CLOSE_ID) != null) {
//                performGlobalAction(GLOBAL_ACTION_BACK);
//                return;
//            }
//        }

    }

    /**
     * 点击开红包按钮
     */
    private void clickOpen() {
        //等待红包弹窗完成，直接使用模拟点击比较快
        SystemClock.sleep(100);
        for (int i = 0; i < 20; i++) {
            SystemClock.sleep(10);
            //计算了一下这个開字在屏幕中的位置，按照屏幕比例计算
            clickOnScreen(screenWidth / 2, screenHeight * POINT_Y_SCAL, 1, null);
        }

        AccessibilityNodeInfo target = findViewByID(RED_PACKET_OPEN);
        if (target != null) {
            performViewClick(target);
            return;
        } else {
            //如果没有找到按钮，再进行模拟点击
            for (int i = 0; i < 20; i++) {
                SystemClock.sleep(10);
                clickOnScreen(screenWidth / 2, screenHeight * POINT_Y_SCAL, 1, null);
            }
        }
    }


    /**
     * 进行消息列表未领取红包的点击
     *
     * @param nodeInfo
     */
    private void clickItem(AccessibilityNodeInfo nodeInfo) {
        //遍历消息列表的每个消息
        for (int i = 0; i < nodeInfo.getChildCount(); i++) {
            //获取到子控件
            AccessibilityNodeInfo nodeInfoChild = nodeInfo.getChild(i);
            //获取红包控件
            AccessibilityNodeInfo target = findViewByID(nodeInfoChild, AUM_ID);
            //如果允许抢自己的红包，直接点击
            if (target != null) {
                //已领取这个控件为空，红包还没有被领取
                if (findViewByID(nodeInfoChild, AUL_ID) == null) {
                    //点击红包控件
                    openPacketDelay(target);
                    return;
                }
            }

            //获取头像的控件
//            AccessibilityNodeInfo avatar = findViewByID(nodeInfoChild, AVATAR_ID);
//            boolean selfLuckMoney = false;
//            //获取头像的位置，判断红包是否是自己发的，自己发的不抢
//            if (avatar != null) {
//                Rect rect = new Rect();
//                avatar.getBoundsInScreen(rect);
//                if (rect.left > screenWidth / 2) {
//                    selfLuckMoney = true;
//                }
//            }
//            //如果不是自己发的红包，并且获取到的微信红包这个控件不为空
//            if (target != null && !selfLuckMoney) {
//                //已领取这个控件为空，红包还没有被领取
//                if (findViewByID(nodeInfoChild, AUL_ID) == null) {
//                    //点击红包控件
//                    openPacketDelay(target);
//                    return;
//                }
//            }
        }
    }

    /**
     * 延迟打开红包
     */
    public void openPacketDelay(AccessibilityNodeInfo nodeInfo) {
        //等待红包弹窗完成，直接使用模拟点击比较快
        int openTime = SPDataUtils.getInstance().getInt(SPDataUtils.OPEN_PACKET_TIME_KEY);
        if (openTime != 0) {
            SystemClock.sleep(1000 * openTime);
        }
        performViewClick(nodeInfo);
    }


    /**
     * 进行联系人列表的红包消息点击
     *
     * @param nodeInfo
     */
    private void clickHumanItem(AccessibilityNodeInfo nodeInfo) {
        for (int i = 0; i < nodeInfo.getChildCount(); i++) {
            AccessibilityNodeInfo nodeInfoChild = nodeInfo.getChild(i);
            AccessibilityNodeInfo target = findViewByID(nodeInfoChild, HUMAN_LIST_TXT_ID);
            if (target != null && target.getText() != null && target.getText().toString().contains(HONG_BAO_TXT)) {
                performViewClick(target);
                return;
            }
        }
    }


    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();

        Log.e("111111", "onServiceConnected");

        ScreenUtil.getScreenSize(this);
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        // 创建唤醒锁
        PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "WxService:wakeLock");
        // 获得唤醒锁
        wakeLock.acquire();
        performGlobalAction(GLOBAL_ACTION_BACK);
        SystemClock.sleep(50);
        performGlobalAction(GLOBAL_ACTION_BACK);
        SystemClock.sleep(50);
        performGlobalAction(GLOBAL_ACTION_BACK);
    }


    @Override
    public void onInterrupt() {
        Log.e("111111", "onInterrupt");
    }

}
